<template>
  <div class="users">
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="selectList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" slot="" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <!-- 列表 -->
    <el-table border :data="userList" style="width:100%">
      <el-table-column type="index"> </el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <!-- 状态 -->
      <el-table-column prop="mg_state" label="状态">
        <!-- 作用域插槽 -->
        <template slot-scope="scope">
          <!-- 滑块 -->
          <el-switch
            @change="stateChange(scope.row)"
            v-model="scope.row.mg_state"
          >
          </el-switch>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作">
        <!-- 编辑   按钮-->
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="editDialog(scope.row.id)"
          ></el-button>
          <!-- 删除   按钮-->
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleteUser(scope.row.id)"
          ></el-button>
          <!-- 分配角色  按钮 -->
          <!-- enterable  鼠标是否可以移入tooltip中 -->
          <el-tooltip
            effect="dark"
            content="分配角色"
            placement="top-start"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="setRoleDialog(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 添加用户  对话框 -->
    <el-dialog
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户  对话框-->
    <el-dialog
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="sendRoleDialogVisible"
      width="30%"
      @close="setRoleDialogClosed"
    >
      <div>
        <span>角色：</span>
        <span>{{ roleInfo.role_name}}</span>
      </div>
      <div>
        <span>姓名：</span>
        <span>{{ roleInfo.username}}</span>
      </div>
      <!-- 选择器 -->
      <el-select v-model="selectedId" placeholder="请选择">
        <el-option
        v-for="item in roleSelect"
        :key="item.id"
        :label="item.roleName"
        :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sendRoleDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="sureSaveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 邮箱的正则表达式
      const reg = /^[A-Za-z0-9]+([_\\.][A-Za-z0-9]+)*@([A-Za-z0-9\- ]+\.)+[A-Za-z]{2,6}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkPhone = (rule, value, cb) => {
      // 手机号的正则表达式
      const reg = /^1[3-9]\d{9}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号！'))
    }
    return {
      addForm: {
        // 添加用户 表单内容
        username: ''
      },
      editForm: {}, // 编辑用户 表单内容
      userList: [], // 用户列表数据
      total: 0, // 数据总条数
      queryInfo: {
        query: '', // 搜索关键字
        pagenum: 1, // 当前页
        pagesize: 2 // 每页显示多少条数据
      },
      addDialogVisible: false, // 添加用户对话框显示隐藏
      editDialogVisible: false, // 编辑用户对话框显示隐藏
      addRules: {
        // 添加用户的校验规则
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      editRules: {
        // 添加用户的校验规则
        email: [
          { required: true, message: '请输入合法的邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入合法的手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      sendRoleDialogVisible: false, // 分配角色对话框
      roleInfo: '', // 当前行信息
      selectedId: '', // 下拉选中的角色值
      roleSelect: [], // 下拉列表里面的角色数据
      roleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  mounted() {},
  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      // 获取数据失败
      if (res.meta.status !== 200) {
        this.$message.error('获取用户列表失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听switch开关状态的改变
    async stateChange(userinfo) {
      // 改变后的数据
      console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      console.log(res)
      // 获取数据失败
      if (res.meta.status !== 200) {
        // 更改失败  页面状态变回之前
        userinfo.mg_state = !userinfo.mg_state
        this.$message.error('更改用户状态失败！')
      }
      this.$message.success('更改用户状态成功！')
    },
    handleSizeChange(val) {
      console.log(val)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 查询用户
    selectList() {
      this.getUserList()
    },
    // 关闭对话框
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      // 这里的重置是之前的检验状态
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      // 点击确定  预校验表单
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        // 验证失败
        if (!valid) return false
        // 验证成功
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          // 此处必须加return   不然程序会继续执行下去
          return this.$message.error('添加用户失败！')
        }
        this.$message.error('添加用户成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 添加用户成功后   刷新页面
        this.getUserList()
      })
    },
    // 编辑用户
    async editDialog(id) {
      this.editDialogVisible = true
      console.log(id)
      // 发送编辑用户胡请求
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      this.editForm = res.data
    },
    // 编辑用户  提交
    async editUser(id) {
      // 点击确定  预校验表单
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        // 验证失败
        if (!valid) return false
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          // 此处必须加return   不然程序会继续执行下去
          return this.$message.error('添加用户失败！')
        }
        this.$message.error('添加用户成功！')
        // 隐藏编辑用户的对话框
        this.editDialogVisible = false
        // 编辑用户成功后   刷新页面
        this.getUserList()
      })
    },
    // 删除用户
    // 如果某个函数调用的结果是promise，则可以用await async优化
    async deleteUser(id) {
      const confirmResult = await this.$confirm('是否删除该用户?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      // 删除请求
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        // 此处必须加return   不然程序会继续执行下去
        return this.$message.error('删除用户失败！')
      }
      this.$message.error('删除用户成功！')
      this.getUserList()
    },
    async setRoleDialog(roleInfo) {
      this.roleId = roleInfo.id // 当前用户id
      this.sendRoleDialogVisible = true
      console.log(roleInfo)
      this.roleInfo = roleInfo
      // 获取选择的角色列表
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      this.roleSelect = res.data
    },
    async sureSaveRole() {
      console.log(this.roleInfo.id)
      if (!this.selectedId) {
        return this.$message.error('请选择角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.roleInfo.id}/role`, { rid: this.selectedId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败！')
      }
      this.$message.success('分配角色成功！')
      this.getUserList()
      this.sendRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.roleInfo = {}
      this.selectedId = ''
    }
  }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
  margin-bottom: 15px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}
.el-table {
  margin-top: 15px;
}
// 分页区域
.el-pagination {
  margin-top: 30px;
}
</style>
